package concurent

import (
	"fmt"
	"sync"
	"time"
)

var WG sync.WaitGroup

// 互斥锁  类似java的syncnized
var lock sync.Mutex
var m int = 100

func add() {
	defer WG.Done()
	lock.Lock()
	m += 1
	time.Sleep(time.Millisecond * 10)
	lock.Unlock()
}

func sub() {
	defer WG.Done()
	lock.Lock()
	m -= 1
	time.Sleep(time.Millisecond * 2)
	lock.Unlock()
}

func MutexTest() {
	for i := 0; i < 100; i++ {
		WG.Add(1)
		go add()
		WG.Add(1)
		go sub()
	}
	WG.Wait()
	fmt.Printf("m: %v\n", m)
}
